from pydantic import BaseModel
from typing import Optional
from sqlalchemy import Column, ForeignKey, Integer, String, DateTime,event
from sqlalchemy.orm import relationship
from models.base import Base
from models.role_permission import role_permissions
from models.admin_menu_permission import admin_menu_permission
from datetime import datetime
from sqlalchemy.sql import func

class Permission(Base):
    __tablename__ = 'permissions'

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(255), nullable=False, comment='权限名称')
    description = Column(String(255), nullable=True, comment='权限描述')
    parent_id = Column(Integer, ForeignKey('permissions.id'), nullable=True, comment='父权限ID')
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment='创建时间')
    updated_at = Column(DateTime(timezone=True), onupdate=func.now(), comment='更新时间')
    deleted_at = Column(DateTime, comment='删除时间')

    children = relationship('Permission', backref='parent', remote_side=[id])
    roles = relationship('Role', secondary=role_permissions, back_populates='permissions')

    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

@event.listens_for(Permission, 'before_update')
def receive_before_update(mapper, connection, target):
    target.updated_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")

@event.listens_for(Permission, 'before_insert')
def set_created_at(mapper, connection, target):
    if not target.created_at:
        target.created_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")

# 在模型定义之后添加关系
Permission.menus = relationship(
    "AdminMenu",
    secondary=admin_menu_permission,
    back_populates='permissions'
)

class PermissionSchema(BaseModel):
    id: int
    name: str
    description: Optional[str] = None
    parent_id: Optional[int] = None
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    deleted_at: Optional[datetime] = None

    class Config:
        orm_mode = True
        json_encoders = {
            datetime: lambda v: v.strftime('%Y-%m-%d %H:%M:%S') if v else None
        }
        from_attributes = True

